<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>校园路网编辑工具</title>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=bVVCCf1URFGnRzeV09G3CJ2iYdl9Fx0o&s=1"></script>
    <script type="text/javascript" src="https://api.map.baidu.com/library/DistanceTool/1.2/src/DistanceTool_min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body, html {
            width: 100%;
            height: 100%;
            font-family: "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
            overflow: hidden;
        }
        .container {
            display: flex;
            height: 100vh;
        }
        .map-area {
            width: 75%;
            height: 100vh;
            position: relative;
        }
        #map {
            width: 100%;
            height: 100%;
        }
        .control-panel {
            width: 25%;
            height: 100vh;
            background-color: #f5f5f5;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }
        .panel-section {
            background-color: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .panel-section h2 {
            color: #333;
            margin-bottom: 15px;
            font-size: 18px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .action-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 15px;
        }
        .action-button {
            padding: 10px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            flex: 1;
            min-width: 120px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .action-button i {
            margin-right: 8px;
        }
        .action-button.active {
            background-color: #2980b9;
            box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        }
        .action-button:hover {
            background-color: #2980b9;
        }
        .action-button.clear {
            background-color: #e74c3c;
        }
        .action-button.clear:hover {
            background-color: #c0392b;
        }
        .action-button.save {
            background-color: #2ecc71;
        }
        .action-button.save:hover {
            background-color: #27ae60;
        }
        .node-info {
            margin-bottom: 15px;
        }
        .node-info label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: bold;
        }
        .node-info input, .node-info select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        .path-info {
            margin-bottom: 15px;
        }
        .path-info label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: bold;
        }
        .path-info input, .path-info select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        .path-info .checkbox-group {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .path-info .checkbox-group input[type="checkbox"] {
            width: auto;
            margin-right: 10px;
            margin-bottom: 0;
        }
        .stats-section {
            font-size: 14px;
            color: #555;
        }
        .stats-section p {
            margin-bottom: 5px;
        }
        .list-section {
            max-height: 200px;
            overflow-y: auto;
            margin-top: 10px;
        }
        .list-item {
            padding: 8px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .list-item:hover {
            background-color: #f9f9f9;
        }
        .list-item-actions {
            display: flex;
            gap: 5px;
        }
        .list-item-actions button {
            padding: 3px 8px;
            background-color: #f1c40f;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .list-item-actions button.delete {
            background-color: #e74c3c;
        }
        .status-message {
            margin-top: 10px;
            padding: 10px;
            border-radius: 5px;
            color: white;
            background-color: #3498db;
            display: none;
        }
        .status-message.success {
            background-color: #2ecc71;
        }
        .status-message.error {
            background-color: #e74c3c;
        }
        .distance-tool-info {
            position: absolute;
            bottom: 10px;
            left: 10px;
            background: rgba(255,255,255,0.8);
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 12px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="map-area">
            <div id="map"></div>
            <div class="distance-tool-info">右键点击地图可以启用测距工具</div>
        </div>
        
        <div class="control-panel">
            <div class="panel-section">
                <h2>路网编辑工具</h2>
                
                <div class="action-buttons">
                    <button id="add-node-btn" class="action-button">
                        <i class="fas fa-map-marker-alt"></i> 添加节点
                    </button>
                    <button id="add-path-btn" class="action-button">
                        <i class="fas fa-road"></i> 添加路径
                    </button>
                    <button id="clear-selection-btn" class="action-button clear">
                        <i class="fas fa-times"></i> 清除选择
                    </button>
                </div>
                
                <div id="node-info-form" class="node-info" style="display: none;">
                    <h3>节点信息</h3>
                    <label for="node-name">名称:</label>
                    <input type="text" id="node-name" placeholder="节点名称">
                    
                    <label for="node-type">类型:</label>
                    <select id="node-type">
                        <option value="junction" selected>路口</option>
                        <option value="building">建筑</option>
                        <option value="gate">门口</option>
                        <option value="poi">兴趣点</option>
                    </select>
                    
                    <label for="node-place-id">关联地点ID (可选):</label>
                    <input type="number" id="node-place-id" placeholder="输入地点ID">
                    
                    <button onclick="saveNode()" class="action-button save">保存节点</button>
                    <button onclick="clearTempMarkers()" class="action-button clear">取消</button>
                </div>
                
                <div id="path-info-form" class="path-info" style="display: none;">
                    <h3>路径信息</h3>
                    <label for="path-name">路径名称:</label>
                    <input type="text" id="path-name" placeholder="输入路径名称">
                    
                    <label for="path-level">路径级别:</label>
                    <select id="path-level">
                        <option value="1">主干道</option>
                        <option value="2" selected>次干道</option>
                        <option value="3">辅助道</option>
                    </select>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" id="allow-bike" checked>
                        <label for="allow-bike">允许骑行</label>
                    </div>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" id="bidirectional" checked>
                        <label for="bidirectional">双向通行</label>
                    </div>
                    
                    <label for="congestion-base">基础拥挤度(0-1):</label>
                    <input type="number" id="congestion-base" step="0.1" min="0" max="1" value="0.7">
                    
                    <button onclick="savePath()" class="action-button save">保存路径</button>
                    <button onclick="clearTempMarkers()" class="action-button clear">取消</button>
                </div>
                
                <div id="status-message" class="status-message"></div>
            </div>
            
            <div class="panel-section stats-section">
                <h2>网络统计</h2>
                <p>节点数量: <span id="node-count">0</span></p>
                <p>路径数量: <span id="path-count">0</span></p>
                <p>总路径长度: <span id="total-length">0</span> 米</p>
            </div>
            
            <div class="panel-section">
                <h2>节点列表</h2>
                <div id="node-list" class="list-section"></div>
            </div>
            
            <div class="panel-section">
                <h2>路径列表</h2>
                <div id="path-list" class="list-section"></div>
            </div>
            
            <div class="panel-section">
                <h2>数据导入/导出</h2>
                <div class="action-buttons">
                    <button id="export-btn" class="action-button">
                        <i class="fas fa-file-export"></i> 导出数据
                    </button>
                    <button id="init-nodes-btn" class="action-button">
                        <i class="fas fa-map-marked-alt"></i> 从POI初始化节点
                    </button>
                </div>
            </div>
            
            <!-- 高级操作 -->
            <div class="panel-section">
                <h2>高级操作</h2>
                <div class="action-buttons">
                    <button onclick="initNodesFromPOI()" class="action-button">
                        <i class="fas fa-map-marked-alt"></i> 从POI初始化节点
                    </button>
                    <button onclick="exportNetworkData()" class="action-button">
                        <i class="fas fa-download"></i> 导出数据
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let map;
        let distanceTool;
        let nodes = [];
        let paths = [];
        let markers = [];
        let polylines = [];
        let selectedNodes = [];
        let tempPolyline = null;
        let currentMode = 'none';
        
        function initMap() {
            try {
                console.log("开始初始化地图...");
                
                map = new BMap.Map('map');
                map.enableScrollWheelZoom(true);
                
                const defaultPoint = new BMap.Point(116.317547, 39.99887); 
                map.centerAndZoom(defaultPoint, 16);
                
                map.addControl(new BMap.NavigationControl());  
                map.addControl(new BMap.ScaleControl());      
                map.addControl(new BMap.OverviewMapControl()); 
                map.addControl(new BMap.MapTypeControl());    
                
                try {
                    distanceTool = new BMapLib.DistanceTool(map);
                    map.addEventListener("rightclick", function(e){
                        distanceTool.open();
                    });
                    console.log("测距工具初始化成功");
                } catch (error) {
                    console.error("测距工具初始化失败：", error);
                    showStatusMessage('测距工具初始化失败。您可以右键点击"显示距离工具"来手动启用它。', 'error');
                }
                
                map.addEventListener('click', handleMapClick);
                
                loadNodes();
                loadPaths();
                
                console.log("地图初始化完成");
            } catch (error) {
                console.error("地图初始化失败：", error);
                alert("地图初始化失败：" + error.message + "\n请刷新页面重试。");
            }
        }
        
        function handleMapClick(e) {
            console.log("地图点击事件触发，当前模式：", currentMode);
            
            if (currentMode === 'add-node') {
                const point = e.point;
                console.log("添加节点位置：", point.lng, point.lat);
                showNodeForm(point);
            } else if (currentMode === 'add-path' && selectedNodes.length < 2) {
                const point = e.point;
                const nearestNode = findNearestNode(point);
                if (nearestNode) {
                    console.log("选择了节点：", nearestNode.id, nearestNode.name);
                    if (selectedNodes.length === 0 || selectedNodes[0].id !== nearestNode.id) {
                        selectNode(nearestNode);
                    }
                } else {
                    console.log("附近没有找到节点");
                    showStatusMessage("附近没有节点，请先添加节点。", "error");
                }
            }
        }
        
        function findNearestNode(point) {
            let minDist = 0.001;
            let nearestNode = null;
            
            for (const node of nodes) {
                const nodePoint = new BMap.Point(node.longitude, node.latitude);
                const dist = map.getDistance(point, nodePoint);
                if (dist < 70 && (nearestNode === null || dist < minDist)) {
                    minDist = dist;
                    nearestNode = node;
                }
            }
            
            return nearestNode;
        }
        
        function showNodeForm(point) {
            document.getElementById('node-info-form').style.display = 'block';
            document.getElementById('path-info-form').style.display = 'none';
            
            document.getElementById('node-info-form').dataset.lng = point.lng;
            document.getElementById('node-info-form').dataset.lat = point.lat;
            
            document.getElementById('node-name').value = '';
            document.getElementById('node-type').value = 'junction';
            document.getElementById('node-place-id').value = '0';
            
            clearTempMarkers();
            const marker = new BMap.Marker(point);
            marker.setAnimation(BMAP_ANIMATION_BOUNCE);
            map.addOverlay(marker);
            markers.push({ marker, temp: true });
        }
        
        function selectNode(node) {
            selectedNodes.push(node);
            
            const nodePoint = new BMap.Point(node.longitude, node.latitude);
            const marker = new BMap.Marker(nodePoint, {
                icon: new BMap.Icon(
                    "https://api.map.baidu.com/images/marker_red_sprite.png", 
                    new BMap.Size(39, 25),
                    { anchor: new BMap.Size(10, 25) }
                )
            });
            map.addOverlay(marker);
            markers.push({ marker, temp: true, selected: true });
            
            if (selectedNodes.length === 2) {
                drawTempPath();
                showPathForm();
            }
        }
        
        function drawTempPath() {
            if (selectedNodes.length !== 2) return;
            
            const start = new BMap.Point(selectedNodes[0].longitude, selectedNodes[0].latitude);
            const end = new BMap.Point(selectedNodes[1].longitude, selectedNodes[1].latitude);
            
            if (tempPolyline) {
                map.removeOverlay(tempPolyline);
            }
            
            tempPolyline = new BMap.Polyline([start, end], {
                strokeColor: '#3498db',
                strokeWeight: 5,
                strokeOpacity: 0.7,
                strokeStyle: 'dashed'
            });
            
            map.addOverlay(tempPolyline);
        }
        
        function showPathForm() {
            document.getElementById('node-info-form').style.display = 'none';
            document.getElementById('path-info-form').style.display = 'block';
            
            document.getElementById('path-name').value = '';
            document.getElementById('path-level').value = '2';
            document.getElementById('allow-bike').checked = true;
            document.getElementById('bidirectional').checked = true;
            document.getElementById('congestion-base').value = '0.7';
            
            const start = new BMap.Point(selectedNodes[0].longitude, selectedNodes[0].latitude);
            const end = new BMap.Point(selectedNodes[1].longitude, selectedNodes[1].latitude);
            const distance = map.getDistance(start, end).toFixed(1);
            
            document.getElementById('path-info-form').dataset.startNodeId = selectedNodes[0].id;
            document.getElementById('path-info-form').dataset.endNodeId = selectedNodes[1].id;
            document.getElementById('path-info-form').dataset.distance = distance;
        }
        
        function saveNode() {
            try {
                const name = document.getElementById('node-name').value;
                const type = document.getElementById('node-type').value;
                const placeId = parseInt(document.getElementById('node-place-id').value) || 0;
                const lng = parseFloat(document.getElementById('node-info-form').dataset.lng);
                const lat = parseFloat(document.getElementById('node-info-form').dataset.lat);
                
                const node = {
                    name,
                    longitude: lng,
                    latitude: lat,
                    type: type,
                    place_id: placeId
                };
                
                console.log("准备保存节点：", JSON.stringify(node));
                
                fetch('/api/path_nodes', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(node)
                })
                .then(response => {
                    console.log("服务器响应状态：", response.status);
                    if (!response.ok) {
                        return response.text().then(text => {
                            throw new Error(`服务器错误 (${response.status}): ${text}`);
                        });
                    }
                    return response.text();
                })
                .then(text => {
                    console.log("服务器响应文本：", text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        throw new Error(`JSON解析错误: ${e.message}\n响应内容: ${text}`);
                    }
                })
                .then(data => {
                    if (data.id) {
                        showStatusMessage('节点添加成功', 'success');
                        loadNodes();
                        clearTempMarkers();
                        document.getElementById('node-info-form').style.display = 'none';
                    } else {
                        showStatusMessage('节点添加失败: ' + (data.error || data.message || '未知错误'), 'error');
                    }
                })
                .catch(error => {
                    showStatusMessage('节点添加失败: ' + error, 'error');
                    console.error("节点添加失败：", error);
                });
            } catch (error) {
                showStatusMessage('节点添加处理错误: ' + error.message, 'error');
                console.error("节点处理错误：", error);
            }
        }
        
        function savePath() {
            try {
                const name = document.getElementById('path-name').value;
                const pathLevel = parseInt(document.getElementById('path-level').value);
                const allowBike = document.getElementById('allow-bike').checked ? 1 : 0;
                const bidirectional = document.getElementById('bidirectional').checked ? 1 : 0;
                const congestionBase = parseFloat(document.getElementById('congestion-base').value);
                
                const startNodeId = parseInt(document.getElementById('path-info-form').dataset.startNodeId);
                const endNodeId = parseInt(document.getElementById('path-info-form').dataset.endNodeId);
                const distance = parseFloat(document.getElementById('path-info-form').dataset.distance);
                
                // 计算步行和骑行时间（假设步行速度1.2m/s, 骑行速度3.5m/s？
                const walkingTime = Math.ceil(distance / 1.2);
                const ridingTime = Math.ceil(distance / 3.5);
                
                const path = {
                    name,
                    start_node_id: startNodeId,
                    end_node_id: endNodeId,
                    distance,
                    walking_time: walkingTime,
                    riding_time: ridingTime,
                    allow_bike: allowBike,
                    congestion_base: congestionBase,
                    path_level: pathLevel,
                    bidirectional
                };
                
                console.log("准备保存路径：", JSON.stringify(path));
                
                // 发送到服务器
                fetch('/api/paths', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(path)
                })
                .then(response => {
                    console.log("服务器响应状态：", response.status);
                    if (!response.ok) {
                        return response.text().then(text => {
                            throw new Error(`服务器错误 (${response.status}): ${text}`);
                        });
                    }
                    return response.text();
                })
                .then(text => {
                    console.log("服务器响应文本：", text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        throw new Error(`JSON解析错误: ${e.message}\n响应内容: ${text}`);
                    }
                })
                .then(data => {
                    if (data.id) {
                        showStatusMessage('路径添加成功', 'success');
                        // 重新加载路径
                        loadPaths();
                        // 清理临时标记
                        clearTempMarkers();
                        // 隐藏表单
                        document.getElementById('path-info-form').style.display = 'none';
                        // 清空选中的节点
                        selectedNodes = [];
                        currentMode = 'none';
                        document.getElementById('add-path-btn').classList.remove('active');
                    } else {
                        showStatusMessage('路径添加失败: ' + (data.error || data.message || '未知错误'), 'error');
                    }
                })
                .catch(error => {
                    showStatusMessage('路径添加失败: ' + error, 'error');
                    console.error("路径添加失败：", error);
                });
            } catch (error) {
                showStatusMessage('路径添加错误: ' + error.message, 'error');
                console.error("路径添加处理错误：", error);
            }
        }
        
        function loadNodes() {
            console.log("开始加载节点数量...");
            fetch('/api/path_nodes')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误！状态：${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    try {
                        // 先清理已有节点
                        for (const marker of markers) {
                            if (!marker.temp) {
                                map.removeOverlay(marker.marker);
                            }
                        }
                        markers = markers.filter(m => m.temp);
                        
                        nodes = data;
                        console.log(`加载了${nodes.length}个节点`);
                        
                        // 创建新标记
                        for (const node of nodes) {
                            const point = new BMap.Point(node.longitude, node.latitude);
                            const marker = new BMap.Marker(point);
                            
                            // 添加提示信息
                            const label = new BMap.Label(node.name || node.id, {
                                offset: new BMap.Size(20, 0)
                            });
                            marker.setLabel(label);
                            
                            // 添加点击事件
                            marker.addEventListener('click', function() {
                                if (currentMode === 'add-path' && selectedNodes.length < 2) {
                                    const existingNode = selectedNodes.find(n => n.id === node.id);
                                    if (!existingNode) {
                                        selectNode(node);
                                    }
                                }
                            });
                            
                            map.addOverlay(marker);
                            markers.push({ marker, node, temp: false });
                        }
                        
                        // 更新节点列表
                        updateNodeList();
                        // 更新统计信息
                        updateStats();
                    } catch (error) {
                        console.error("节点数据处理错误：", error);
                        showStatusMessage('节点数据处理错误：' + error.message, 'error');
                    }
                })
                .catch(error => {
                    console.error("加载节点数据失败：", error);
                    showStatusMessage('加载节点数据失败：' + error.message, 'error');
                });
        }
        
        function loadPaths() {
            console.log("开始加载路径数量...");
            fetch('/api/paths')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误！状态：${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    try {
                        // 先清理已有路径
                        for (const polyline of polylines) {
                            map.removeOverlay(polyline.polyline);
                        }
                        polylines = [];
                        
                        paths = data;
                        console.log(`加载了${paths.length}条路径`);
                        
                        // 创建新路径
                        for (const path of paths) {
                            const start = new BMap.Point(path.start_lng, path.start_lat);
                            const end = new BMap.Point(path.end_lng, path.end_lat);
                            
                            // 根据路径级别设置颜色
                            let color;
                            let weight;
                            
                            switch (parseInt(path.path_level)) {
                                case 1: // 主干道
                                    color = '#e74c3c';
                                    weight = 8;
                                    break;
                                case 2: // 次干道
                                    color = '#3498db';
                                    weight = 6;
                                    break;
                                case 3: // 辅助道
                                    color = '#2ecc71';
                                    weight = 4;
                                    break;
                                default:
                                    color = '#95a5a6';
                                    weight = 5;
                            }
                            
                            const polyline = new BMap.Polyline([start, end], {
                                strokeColor: color,
                                strokeWeight: weight,
                                strokeOpacity: 0.8
                            });
                            
                            // 只添加路线，不添加标记
                            map.addOverlay(polyline);
                            polylines.push({ polyline, path });
                        }
                        
                        // 更新路径列表
                        updatePathList();
                        // 更新统计信息
                        updateStats();
                    } catch (error) {
                        console.error("路径数据处理错误：", error);
                        showStatusMessage('路径数据处理错误：' + error.message, 'error');
                    }
                })
                .catch(error => {
                    console.error("加载路径数据失败：", error);
                    showStatusMessage('加载路径数据失败：' + error.message, 'error');
                });
        }
        
        function deleteNode(nodeId) {
            if (!confirm('确定要删除此节点吗？如果节点已用于路径，将无法删除。')) {
                return;
            }
            
            fetch(`/api/path_nodes/${nodeId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.message === '节点删除成功') {
                    showStatusMessage('节点删除成功。', 'success');
                    loadNodes();
                } else {
                    showStatusMessage('节点删除失败：' + data.message, 'error');
                }
            })
            .catch(error => {
                showStatusMessage('节点删除失败：' + error, 'error');
            });
        }
        
        function updateNodeList() {
            try {
                const nodeList = document.getElementById('node-list');
                nodeList.innerHTML = '';
                
                for (const node of nodes) {
                    const item = document.createElement('div');
                    item.className = 'list-item';
                    
                    // 节点信息
                    const info = document.createElement('div');
                    info.className = 'list-item-info';
                    info.textContent = `${node.id}: ${node.name || '未命名'} (${node.type})`;
                    
                    // 操作按钮
                    const actions = document.createElement('div');
                    actions.className = 'list-item-actions';
                    
                    const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'delete';
                    deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
                    deleteBtn.addEventListener('click', () => deleteNode(node.id));
                    
                    actions.appendChild(deleteBtn);
                    
                    item.appendChild(info);
                    item.appendChild(actions);
                    
                    nodeList.appendChild(item);
                }
            } catch (error) {
                console.error("更新节点列表错误：", error);
            }
        }
        
        function updatePathList() {
            try {
                const pathList = document.getElementById('path-list');
                pathList.innerHTML = '';
                
                for (const path of paths) {
                    const item = document.createElement('div');
                    item.className = 'list-item';
                    
                    // 路径信息
                    const info = document.createElement('div');
                    info.className = 'list-item-info';
                    info.textContent = `${path.id}: ${path.name || '未命名'} (${path.distance.toFixed(1)}m)`;
                    
                    // 操作按钮
                    const actions = document.createElement('div');
                    actions.className = 'list-item-actions';
                    
                    const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'delete';
                    deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
                    deleteBtn.addEventListener('click', () => deletePath(path.id));
                    
                    actions.appendChild(deleteBtn);
                    
                    item.appendChild(info);
                    item.appendChild(actions);
                    
                    pathList.appendChild(item);
                }
            } catch (error) {
                console.error("更新路径列表错误：", error);
            }
        }
        
        function deletePath(pathId) {
            if (!confirm('确定要删除此路径吗？')) {
                return;
            }
            
            fetch(`/api/paths/${pathId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.message === '路径删除成功') {
                    showStatusMessage('路径删除成功。', 'success');
                    loadPaths();
                } else {
                    showStatusMessage('路径删除失败：' + data.message, 'error');
                }
            })
            .catch(error => {
                showStatusMessage('路径删除失败：' + error, 'error');
            });
        }
        
        function showStatusMessage(message, type) {
            try {
                console.log("Status message：", message, "Type：", type);
                const statusElement = document.getElementById('status-message');
                if (!statusElement) {
                    console.error("Status message element not found");
                    return;
                }
                
                statusElement.textContent = message;
                statusElement.className = 'status-message ' + (type || '');
                statusElement.style.display = 'block';
                
                setTimeout(() => {
                    statusElement.style.display = 'none';
                }, 3000);
            } catch (error) {
                console.error("Error showing status message：", error);
            }
        }
        
        function clearTempMarkers() {
            for (const marker of markers) {
                if (marker.temp) {
                    map.removeOverlay(marker.marker);
                }
            }
            markers = markers.filter(m => !m.temp);
            
            if (tempPolyline) {
                map.removeOverlay(tempPolyline);
                tempPolyline = null;
            }
        }
        
        function clearSelection() {
            clearTempMarkers();
            selectedNodes = [];
            currentMode = 'none';
            document.getElementById('add-node-btn').classList.remove('active');
            document.getElementById('add-path-btn').classList.remove('active');
            document.getElementById('node-info-form').style.display = 'none';
            document.getElementById('path-info-form').style.display = 'none';
        }
        
        function initNodesFromPOI() {
            if (!confirm('此操作将根据数据库中的地点数据初始化节点，是否继续？')) {
                return;
            }
            
            fetch('/api/places')
                .then(response => response.json())
                .then(places => {
                    let added = 0;
                    let errors = 0;
                    
                    function processPlace(index) {
                        if (index >= places.length) {
                            showStatusMessage(`初始化完成！成功添加${added}个节点，失败${errors}个。`, 'success');
                            loadNodes();
                            return;
                        }
                        
                        const place = places[index];
                        
                        const node = {
                            name: place.name,
                            longitude: place.longitude,
                            latitude: place.latitude,
                            type: 'poi',
                            place_id: place.id
                        };
                        
                        fetch('/api/path_nodes', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(node)
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.id) {
                                added++;
                            } else {
                                errors++;
                            }
                            processPlace(index + 1);
                        })
                        .catch(error => {
                            errors++;
                            processPlace(index + 1);
                        });
                    }
                    
                    processPlace(0);
                })
                .catch(error => {
                    showStatusMessage('加载地点数据失败：' + error, 'error');
                });
        }
        
        function exportNetworkData() {
            const data = {
                nodes,
                paths
            };
            
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'campus_network_data.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            showStatusMessage('数据导出成功。', 'success');
        }
        
        function updateStats() {
            document.getElementById('node-count').textContent = nodes.length;
            document.getElementById('path-count').textContent = paths.length;
            
            let totalLength = 0;
            for (const path of paths) {
                totalLength += path.distance;
            }
            document.getElementById('total-length').textContent = totalLength.toFixed(1);
        }
        
        window.onload = function() {
            console.log("页面加载完成，开始初始化...");
            initMap();
            
            // 添加按钮事件绑定
            document.getElementById('add-node-btn').addEventListener('click', function() {
                console.log("点击添加节点按钮");
                clearSelection();
                currentMode = 'add-node';
                this.classList.add('active');
                showStatusMessage('请在地图上点击选择节点位置', 'info');
            });
            
            document.getElementById('add-path-btn').addEventListener('click', function() {
                console.log("点击添加路径按钮");
                clearSelection();
                currentMode = 'add-path';
                this.classList.add('active');
                selectedNodes = [];
                showStatusMessage('请依次点击两个节点来创建路径', 'info');
            });
            
            document.getElementById('clear-selection-btn').addEventListener('click', function() {
                console.log("点击清除选择按钮");
                clearSelection();
                showStatusMessage('已清除所有选择', 'success');
            });
            
            // 导出按钮事件绑定
            document.getElementById('export-btn').addEventListener('click', function() {
                console.log("点击导出按钮");
                exportNetworkData();
            });
            
            // 从POI初始化节点按钮事件绑定
            document.getElementById('init-nodes-btn').addEventListener('click', function() {
                console.log("点击从POI初始化节点按钮");
                initNodesFromPOI();
            });
        };
    </script>
</body>
</html>